package com.zmovie.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.zmovie.admin.constant.Constants;
import com.zmovie.common.utils.MD5Utils;
import com.zmovie.framework.domain.User;
import com.zmovie.framework.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 登录模块
 * @since 2023-11-27 15:40
 */
@Controller
@Api(tags = "后台登录")
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    @ApiOperation("跳转到登录页面")
    public String toLoginPage(){
        return "login";
    }

    @PostMapping("/login.do")
    @ApiOperation("登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    public String login(String username, String password, RedirectAttributes attributes, HttpSession session){
        //参数校验
        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password)){
            attributes.addFlashAttribute(Constants.MESSAGE_KEY, "用户名密码不能为空");
            return "redirect:/login";
        }
        //加密
        password = MD5Utils.code(password);
        User user = userService.checkLogin(username, password);
        if(user != null){
            //判断是否是管理员
            if(user.getRoleId() != 1){  //非管理员
                attributes.addFlashAttribute(Constants.MESSAGE_KEY, "你没有权限");
                return "redirect:/login";
            }
            //登录成功
            user.setPassword(null);
            session.setAttribute(Constants.SESSION_USER_KEY, user);
            return "index";
        }
        //登录失败
        attributes.addFlashAttribute(Constants.MESSAGE_KEY, "用户名或密码错误");
        return "redirect:/login";
    }
    @GetMapping("/logout.do")
    @ApiOperation("登出")
    public String logout(HttpSession session){
        //移除Session中用户信息
        session.removeAttribute(Constants.SESSION_USER_KEY);
        return "redirect:/login";
    }
}
